<?php
class Admin_TourController extends Apps_Controller_Action_Admin {

	//LIST
	public function indexAction() {
		$this->actResolve('act_delete',
						  'delete', null, null, array('id' => $this->_getParam('item_checker')),
					 	  true);

		$tbTour = new M_DbTable_Tour();
		$grid 	= new Apps_Plugin_Grid('tourGrid');

		$grid->setData($tbTour->getList())
			 ->setTableCaption('List Tour')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Title',
			 			  'dataField'   => 'title'),
			 		array('title'		=> 'Category',
			 			  'dataField'   => 'tour_category_title'),
			 		array('title'		=> 'Trip In Style',
			 			  'dataField'   => 'tour_style_title'),
			 		array('title'		=> 'Country',
			 			  'dataField'	=> 'country',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Promotion',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['special_offer'] == M_DbTable_Tour::SPECIAL_OFFER_TRUE)?
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint label label-success" data-ajax-to="/admin/tour/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' :
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint label label-warning" data-ajax-to="/admin/tour/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Public',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['status'] == M_DbTable_Tour::STATUS_ACTIVE)?
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/tour/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' :
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/tour/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Photo',
			 			  'width'       => '2%',
			 			  'html'        => array('<a href="/admin/photo-management/tour?id=%s"><i class="icon-folder-open" title="Quản lý ảnh"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center'),
			 		array('title'		=> 'View',
			 			  'html'        => array('<a href="/tour/detail?id=%s" target="_blank"><i class="icon-list-alt"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center'),
			 		array('title'       => 'Edit',
			 			  'html'        => array('<a href="/admin/tour/edit?id=%s"><i class="icon-edit" title="Sửa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%'),
			 	    array('title'       => 'Delete',
			 			  'html'        => array('<a href="/admin/tour/delete?id=%s" class="must-confirm" data-must-confirm-msg="Bạn có chắc là muốn xóa?"><i class="icon-remove" title="Xóa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center')
			 		));
		$grid->applySearch(new Admin_Form_Search_Tour());

		$this->view->grid = $grid;
	}

	//ADD
	public function addAction() {
		$rq 		= $this->_request;
		$f 			= new Admin_Form_AddTour();
		$tbTour		= new M_DbTable_Tour();
		$tbArticle 	= new M_DbTable_Article();

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_TOUR);
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;

				$data = $f->getValues();

				//resize images
				try {
				    $thumbnailNew = str_replace('/tour/', '/tour/thumbnail_', $thumbnail);
				    $image = new Apps_Plugin_ResizeImages();
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(156);
				    $image->save(PUBLIC_PATH .$thumbnailNew);

				    //detail thumbnail;
				    $detailThumbnail = str_replace('/tour/', '/tour/detail_thumbnail_', $thumbnail);
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(366);
				    $image->save(PUBLIC_PATH .$detailThumbnail);

				} catch (Exception $e) {
				    //Excetion here
				}

				$data['thumbnail'] 		= $thumbnailNew;
				$data['detail_thumbnail'] = $detailThumbnail;


				$keyFilterTour = array('tour_category_id',
									   'tour_style_id',
									   'special_offer',
									   'country_id',
									   'itinerary',
									   'en_itinerary',
									   'price',
									   'en_price',
									   'note_price',
									   'en_note_price',
									   'meta_keyword',
									   'meta_description',
									   'header_title',
				                       'detail_thumbnail');

				$tourId = $tbTour->safelyInsert($data, $keyFilterTour);

				if ($tourId) {
				    //add price table
				    $tbTourHotel      = new M_DbTable_TourHotel();
				    $tbTourHotelPrice = new M_DbTable_TourHotelPrice();

				    $hotelName = $rq->getParam('hotel_name');
				    $hotelRate = $rq->getParam('hotel_rating');
				    $sgl       = $rq->getParam('sgl');

				    foreach($hotelName as $k => $v) {
                        if($v) {
                            $tourHotel = array('tour_id'      => $tourId,
                                               'hotel_name'   => $v,
                                               'hotel_rating' => $hotelRate[$k],
                                               'sgl_supp'     => $sgl[$k]);

                            $tourHotelId = $tbTourHotel->insert($tourHotel);

                            if($tourHotelId) {
                                for($i = 0; $i < 5; $i++) {
                                    $price = $rq->getParam('price_'.($i + 1));
                                    $tourHotelPrice = array('tour_hotel_id'   => $tourHotelId,
                                                            'number_customer' => $rq->getParam('number_customer_'.($i + 1)),
                                                            'price'           => $price[$k]);

                                    $tbTourHotelPrice->insert($tourHotelPrice);
                                }
                            }
                        }
				    }
					$this->_flashMessenger->addMessage(
						$tbArticle->addArticle($data, $tourId, $tbArticle::REFERENCE_TYPE_TOUR)
						? self::$msgAddSuccess
						: self::$msgAddFailed
					);
				}
				$this->_helper->redirector('index', null, null);
			}
		}
		
		//rename label: detail->overview detail
		$detailElement = $f->getElement('en_detail');
		$detailElement->setLabel('Overview (En) - tour detail');
		
		$detailElement = $f->getElement('detail');
		$detailElement->setLabel('Overview (Vi) - tour detail');
		
		$this->view->form = $f;
	}

	//EDIT TOUR
	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		$tbTour = new M_DbTable_Tour();
		$tour 	= $tbTour->getTour($id);

		if (!$id || !$tour) {
			$this->_helper->redirector('index');
		}

		$f = new Admin_Form_AddTour();
		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				$tbArticle 	= new M_DbTable_Article();

				// Upload thumbnail - replace thumbnail if changed
				$rs = $tbArticle->getArticleByReference($id, $tbArticle::REFERENCE_TYPE_TOUR)->query()->fetch();
				$thumbnail = $rs['thumbnail'];

				if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_TOUR);

					$uploaded = $uploader->upload();
					if($uploaded) {
					    // Delete ex-thumbnail: Yes 3 ảnh: 1 ảnh gốc, 2 ảnh resize: thumbnail, detail-thumbnail
						unlink(Apps_Plugin_Upload_File::getPath($thumbnail));
						unlink(Apps_Plugin_Upload_File::getPath(str_replace('/tour/thumbnail_', '/tour/', $thumbnail))); // Delete thumbnail
						unlink(Apps_Plugin_Upload_File::getPath(str_replace('/tour/thumbnail_', '/tour/detail_thumbnail_', $thumbnail))); // Delete ex-detail thumbnail

						$thumbnail = $uploaded['thumbnail']['uri'];

						//resize images
						try {
        				    $thumbnailNew = str_replace('/tour/', '/tour/thumbnail_', $thumbnail);
    						$image = new Apps_Plugin_ResizeImages();
        				    $image->load(PUBLIC_PATH .$thumbnail);
        				    $image->resizeToWidth(156);
        				    $image->save(PUBLIC_PATH .$thumbnailNew);

        				    //detail thumbnail;
        				    $detailThumbnail = str_replace('/tour/', '/tour/detail_thumbnail_', $thumbnail);
        				    $image->load(PUBLIC_PATH .$thumbnail);
        				    $image->resizeToWidth(366);
        				    $image->save(PUBLIC_PATH .$detailThumbnail);
						} catch (Exception $e) {
						    //Excetion here
						}
					}
				}

				$data = $f->getValues();
				$data['thumbnail'] = $thumbnailNew;
				$data['detail_thumbnail'] = $detailThumbnail;

				$keyFilterTour = array('tour_category_id',
									   'tour_style_id',
									   'special_offer',
									   'country_id',
									   'itinerary',
									   'en_itinerary',
									   'price',
									   'en_price',
                				       'note_price',
                				       'en_note_price',
									   'meta_keyword',
									   'meta_description',
									   'header_title',
									   'detail_thumbnail');

				$rT = $tbTour->safelyUpdate($data, array('id =?' => $id) , $keyFilterTour);
				$rA = $tbArticle->updateArticle($data, $id, $tbArticle::REFERENCE_TYPE_TOUR);

				//to edit price: delete old price then add new price
			    //add price table
			    $tbTourHotel      = new M_DbTable_TourHotel();
			    $tbTourHotelPrice = new M_DbTable_TourHotelPrice();
			    $tbTourHotel->delete(array('tour_id =?' => $id));

			    $hotelName = $rq->getParam('hotel_name');
			    $hotelRate = $rq->getParam('hotel_rating');
			    $sgl       = $rq->getParam('sgl');

			    foreach($hotelName as $k => $v) {
                    if($v) {
                        $tourHotel = array('tour_id'      => $id,
                                           'hotel_name'   => $v,
                                           'hotel_rating' => $hotelRate[$k],
                                           'sgl_supp'     => $sgl[$k]);
                        $tourHotelId = $tbTourHotel->insert($tourHotel);
                        if($tourHotelId) {
                            for($i = 0; $i < 5; $i++) {
                                $price = $rq->getParam('price_'.($i + 1));
                                $tourHotelPrice = array('tour_hotel_id'   => $tourHotelId,
                                                        'number_customer' => $rq->getParam('number_customer_'.($i + 1)),
                                                        'price'           => $price[$k]);
                                $tbTourHotelPrice->insert($tourHotelPrice);
                            }
                        }
                    }
			    }

				if (!$rT && !$rA) {
					$this->_flashMessenger->addMessage(self::$msgUpdateFailed);
				} else {
					$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				}
				$this->_helper->redirector('index');
			}
		}
		//populate price table
		$tbTourHotel      = new M_DbTable_TourHotel();
        $tbTourHotelPrice = new M_DbTable_TourHotelPrice();

        $tourHotel = $tbTourHotel->fetchAll(array('tour_id =?' => $id))->toArray();
        foreach($tourHotel as $k => $v) {
            $tourHotel[$k]['price'] = $tbTourHotelPrice->fetchAll(array('tour_hotel_id =?' => $v['id']))->toArray();
        }
        //Zend_Debug::dump($tourHotel);die;
        $this->view->tourHotel = $tourHotel;

		$f->setLegend('Edit Tour');
		$f->populate($tour->query()->fetch());
		
		//rename label: detail->overview detail
		$detailElement = $f->getElement('en_detail');
		$detailElement->setLabel('Overview (En) - tour detail');
		
		$detailElement = $f->getElement('detail');
		$detailElement->setLabel('Overview (Vi) - tour detail');
		
		$this->view->form = $f;
		$this->render('add');
	}

	//DELETE
	public function deleteAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		if (!$id) {
			$this->_helper->redirector('index');
		}

		$tbTour = new M_DbTable_Tour();
		$tbArticle = new M_DbTable_Article();

		if (is_numeric($id)) {
			if ($tbTour->safelyDelete('id ='. $id)) {
				$this->_flashMessenger->addMessage(
					$tbArticle->deleteArticle($id, $tbArticle::REFERENCE_TYPE_TOUR)
					? self::$msgDeleteSuccess
					: self::$msgDeleteError
				);
			}
		} elseif (is_array($id)) {
			foreach ($id as $v) {
				if ($tbTour->safelyDelete('id ='. $v)) {
					$tbArticle->deleteArticle($v, $tbArticle::REFERENCE_TYPE_TOUR);
				}
			}
		}

		$this->_helper->redirector('index');
	}

	public function changeValueAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$param  = $rq->getParam('p');
		$id 	= intval($rq->getParam('id'));
		$tbTour = new M_DbTable_Tour();
		if(!($r = $tbTour->fetchRow(array('id = ?' => $id))->toArray())) {
			echo '<script>window.location=window.location</script>
				<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
				. $this->getBacktrackUrl()
				. '">Update Error (Record not found), please wait ...</a>';
		}

		switch ($param) {
			case 'offer':
				($r['special_offer'] == M_DbTable_Tour::SPECIAL_OFFER_TRUE) ?
					$tbTour->safelyUpdate(array('special_offer' 		=> M_DbTable_Tour::SPECIAL_OFFER_FALSE),
										   array('special_offer = ?' 	=> M_DbTable_Tour::SPECIAL_OFFER_TRUE,
										   		 'id =?'				=> $id)) :
					$tbTour->safelyUpdate(array('special_offer' 		=> M_DbTable_Tour::SPECIAL_OFFER_TRUE),
										   array('special_offer = ?' 	=> M_DbTable_Tour::SPECIAL_OFFER_FALSE,
										   		 'id =?'				=> $id));
				break;

			case 'public':
				($r['status'] == M_DbTable_Tour::STATUS_ACTIVE) ?
					$tbTour->safelyUpdate(array('status'  => M_DbTable_Tour::STATUS_INACTIVE),
										  array('id =?'	  => $id)) :
					$tbTour->safelyUpdate(array('status'  => M_DbTable_Tour::STATUS_ACTIVE),
										   array('id =?'  => $id));
				break;


			default: break;
		}

		echo '<script>document.location.reload()</script>
			<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
			. $this->getBacktrackUrl()
			. '">Update successfully, please wait ...</a>';
	}

}